<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="供应商" prop="tenantId" v-if="isPla">
        <el-select v-model="queryParams.tenantId" placeholder="请选择供应商" clearable size="small">
           <el-option
            v-for="item in tenantList"
            :key="item.tenantId"
            :label="item.name"
            :value="item.tenantId">
          </el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="商品类型" align="center" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择商品类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.goods_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
       <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
           <el-option
            v-for="dict in dict.type.goods_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:goodsWarehouse:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:goodsInfo:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:goodsInfo:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['biz:goodsWarehouse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsWarehouseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="goodsWarehouseId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品图片" align="center" prop="goodsImg">
         <template slot-scope="scope">
          <el-image v-if="scope.row.goodsImg!=null" style="width:70px; height:70px" :src="scope.row.goodsImg" :preview-src-list="getImgs(scope.row.goodsImg)"></el-image>
         </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="carouselImg">
        <template slot-scope="scope">
          <el-image v-if="scope.row.carouselImg!=null" style="width:70px; height:70px" :src="getImg(scope.row.carouselImg)" :preview-src-list="getImgs(scope.row.carouselImg)"></el-image>
         </template>
      </el-table-column>
      <el-table-column label="成本价" align="center" prop="costPrice"/>
      <el-table-column label="市场价" align="center" prop="marketPrice"/>
      <el-table-column label="规格" align="center" prop="specs"/>
      <el-table-column label="商品类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="总库存" align="center" prop="stockTotal" />
      <el-table-column label="已售库存" align="center" prop="soldStock" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="供应商" align="center" prop="tenantName" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateStatus(scope.row)"
            v-hasPermi="['biz:goodsWarehouse:edit']"
          >{{scope.row.status==0?"上架":scope.row.status==2?"上架":"下架"}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:goodsWarehouse:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:goodsWarehouse:remove']"
            v-show="!scope.row.isGenRedeemCode"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model.trim="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsImg">
          <imageUpload v-model="form.goodsImg" :limit="1"/>
        </el-form-item>
        <el-form-item label="轮播图" prop="carouselImg">
           <imageUpload v-model="form.carouselImg" :limit="5"/>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
            <el-radio v-model="form.type" :label="0">实物商品</el-radio>
            <el-radio v-model="form.type" :label="1">虚拟商品<span style="font-size:10px; color:red">  (*虚拟商品库存设置请去导入库存excel文件)</span></el-radio>
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
           <el-input v-model.trim="form.costPrice" type="number" />
        </el-form-item>
        <el-form-item label="市场价" prop="marketPrice">
           <el-input v-model.trim="form.marketPrice" type="number" />
        </el-form-item>
        <el-form-item label="规格" prop="specs">
          <el-input v-model.trim="form.specs" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="详细信息" prop="details">
          <editor v-model="form.details" :min-height="192" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="总库存" prop="stockTotal" v-show="form.type==0">
          <el-input type="number" v-model="form.stockTotal" placeholder="请输入总库存" />
        </el-form-item>
        <!-- <el-form-item label="供应商" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择供应商" filterable clearable size="small">
            <el-option
              v-for="item in tenantList"
              :key="item.tenantId"
              :label="item.name"
              :value="item.tenantId">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoodsWarehouse, getGoodsWarehouse, delGoodsWarehouse, addGoodsWarehouse, updateGoodsWarehouse, exportGoodsWarehouse, updateStatus } from "@/api/biz/goodsInfo/goodsWarehouse";
import { isPlatform, listNotPage } from "@/api/system/tenant"
export default {
  name: "GoodsWarehouse",
  dicts: ['goods_type','goods_status'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      goodsWarehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 租户列表
      tenantList: [],
      isPla: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        goodsImg: null,
        carouselImg: null,
        specs: null,
        details: null,
        stockTotal: null,
        resStock: null,
        soldStock: null,
        tenantId: null,
        status: null
      },
      // 表单参数
      form: {
        type: 0
      },
      // 表单校验
      rules: {
        goodsName:[
          {required:true, message:"商品名称不能为空", trigger:"blur"}
        ],
        goodsImg:[
          {required:true, message:"商品图片不能为空", trigger:"blur"}
        ],
        carouselImg:[
          {required:true, message:"商品轮播图不能为空", trigger:"blur"}
        ],
        costPrice:[
          {required:true, message:"商品成本价不能为空", trigger:"blur"}
        ],
        marketPrice:[
          {required:true, message:"商品市场价不能为空", trigger:"blur"}
        ],
        specs:[
          {required:true, message:"商品规格不能为空", trigger:"blur"}
        ],
        details:[
          {required:true, message:"商品详情不能为空", trigger:"blur"}
        ],
        stockTotal:[
          {required:true, message:"商品库存不能为空", trigger:"blur"}
        ],
        tenantId:[
          {required:true, message:"供应商不能为空", trigger:"blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getIsPlatform();
    this.getTenantList();
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listGoodsWarehouse(this.queryParams).then(response => {
        this.goodsWarehouseList = response.rows;
        this.total = Number(response.total);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsWarehouseId: null,
        goodsName: null,
        goodsImg: null,
        carouselImg: null,
        specs: null,
        details: null,
        stockTotal: 0,
        resStock: null,
        soldStock: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        tenantId: null,
        costPrice: null,
        marketPrice: null,
        type: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsWarehouseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsWarehouseId = row.goodsWarehouseId || this.ids
      getGoodsWarehouse(goodsWarehouseId).then(response => {
        this.form = response.data;
        //this.form.stockTotal = response.data.stockTotal+response.data.soldStock;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const regex = /^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
          if(!regex.test(this.form.costPrice)){
            return this.$message.error("成本价金额格式不正确");
          }
          if(!regex.test(this.form.marketPrice)){
            return this.$message.error("市场价金额格式不正确");
          }
          if(this.form.stockTotal < this.form.soldStock){
            return this.$message.error("总库存不能小于已售库存（" + this.form.soldStock +")");
          }
          if (this.form.goodsWarehouseId != null) {
            updateGoodsWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsWarehouseIds = row.goodsWarehouseId || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + goodsWarehouseIds + '"的数据项？').then(function() {
        return delGoodsWarehouse(goodsWarehouseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有商品信息数据项？').then(() => {
        this.exportLoading = true;
        return exportGoodsWarehouse(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    getImg(value){
      let arr=value.split(",");
      return arr[0];
    },
    getImgs(urls){
      let arr=urls.split(",");
      for(let i=0;i<arr.length;i++){
        arr[i]=arr[i];
      }
      return arr;
    },
    //租户列表
    getTenantList(){
      listNotPage().then(res => {
        if(res.code==200){
          this.tenantList=res.data;
        }
      })
    },
    //是否是平台
    getIsPlatform(){
      isPlatform().then(res => {
       if(res.code==200){
          this.isPla=res.data;
        }
      })
    },
    //上下架商品
    updateStatus(row){
      let status=row.status==0?1:row.status==2?1:2
      let data={
        "goodsWarehouseId":row.goodsWarehouseId,
        "status":status
      }
      updateStatus(data).then(res=>{
         if(res.code==200 && res.data==1){
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.getList();
        }
      })
    }
  }
};
</script>
